using System.Collections.Generic;

#nullable enable

namespace ZFramework
{
    public interface IRegistable
	{
		int Index { get; set; }
	}

	public class Registry<K, V>
		where K : notnull
		where V : notnull, IRegistable
	{
		private readonly Dictionary<K, int> _indices = [];
		private readonly List<V> _entries = [];

		public bool Empty => _entries.Count == 0;

		public void AddEntry(K id, V entry)
		{
			var index = _entries.Count;
			entry.Index = index;
			_indices.Add(id, index);
			_entries.Add(entry);
		}

		public void Clear()
		{
			_indices.Clear();
			_entries.Clear();
		}

		public V? GetEntry(int index)
		{
			if (index >= 0 && index < _entries.Count)
				return _entries[index];
			return default;
		}

		public V? GetEntryById(K id) => _indices.TryGetValue(id, out int index) ? GetEntry(index) : default;

		public int? GetIndex(K id) => _indices.TryGetValue(id, out int index) ? index : null;

		public K? GetId(int index)
		{
			foreach (var (key, value) in _indices)
			{
				if (value == index)
					return key;
			}
			return default;
		}
	}
}